
#include "HrkObject.h"
#include "HrkNode.h"
#include "HrkMesh.h"

IMPLEMENT_DYNCREATE( CHrkObject,CBaseObject )

HrkObType StrType2Hrk( const TCHAR* sType )
{
	if( strcmp( sType,"Root" ) == 0 ){
		return HRK_ROOT;
	}
	else if( strcmp( sType,"Node" )  == 0 ){
		return HRK_NODE;
	}
	else if( strcmp( sType,"Bone" )  == 0 ){
		return HRK_BONE;
	}
	else if( strcmp( sType,"Mesh" )  == 0 ){
		return HRK_MESH;
	}
	else if( strcmp( sType,"SubMesh" )  == 0 ){
		return HRK_SUBMESH;
	}
	else if( strcmp( sType,"Light" )  == 0 ){
		return HRK_LIGHT;
	}
	else if( strcmp( sType,"Helper" )  == 0 ){
		return HRK_HELPER;
	}
	else if( strcmp( sType,"Camera" )  == 0 ){
		return HRK_CAMERA;
	}

	return HRK_UNKNOWN;
}

CHrkNode* MakeHrkNode( HrkObType type )
{
	CHrkNode* node = new CHrkNode;
	
	CHrkObject* obj = NULL;
	
	if( type == HRK_ROOT ){	

	}
	else if( type == HRK_NODE ){
		
	}
	else if( type == HRK_BONE ){
		
	}
	else if( type == HRK_MESH ){		
		obj = new CHrkMesh;
		obj->m_ob_type = HRK_MESH;
	}
	else if( type == HRK_SUBMESH ){		
		obj = new CHrkMesh;
		obj->m_ob_type = HRK_MESH;
		CHrkSubMesh* subMesh = new CHrkSubMesh;
		subMesh->m_ob_type = HRK_SUBMESH;
		dynamic_cast<CHrkMesh*>(obj)->m_subMeshesVec.push_back( subMesh );
	}
	else if( type == HRK_LIGHT ){
		obj = new CHrkObject;	
		obj->m_ob_type = HRK_LIGHT;
	}
	else if( type == HRK_HELPER ){
		obj = new CHrkObject;	
		obj->m_ob_type = HRK_HELPER;
	}
	else if( type == HRK_CAMERA ){
		obj = new CHrkObject;	
		obj->m_ob_type = HRK_CAMERA;
	}
	else if( type == HRK_UNKNOWN ){
		obj = new CHrkObject;	
		obj->m_ob_type = HRK_CAMERA;
	}
	
	node->m_ob_type = type;
	node->m_object = obj;

	return node;
}

CHrkObject::CHrkObject()
{
	m_slot = -1;
	m_parent = NULL;
	m_RefCount = 0;
	m_ob_type = HRK_UNKNOWN;

	m_translate.Clear();
	m_rotate.Clear();
	m_scale = GLvec3f( 1.f,1.f,1.f );

	m_translate1.Clear();
	m_rotate1.Clear();
	m_scale1 = GLvec3f( 1.f,1.f,1.f );

	m_mat.Identity();
	m_mat_comb.Identity();

	AddRef();
}

CHrkObject::~CHrkObject()
{
	Release();
}

int CHrkObject::GetSlotIndex()
{
	return m_slot;
}

void CHrkObject::UpdateTransform()
{
}

void CHrkObject::ParseScript( TiXmlElement* elem )
{
}

int CHrkObject::FindSlotIndex()
{
	assert( m_parent->IsA( RUNTIME_CLASS( CHrkNode )));

	CHrkNode* node = static_cast<CHrkNode*>( m_parent );

	if( m_parent!=this)
		return -1;

	int nChilds = node->m_child_list.Count();
	for( int i = 0;i<nChilds;i++ ){
		if( node->m_child_list[i] == this ){
			return i;
		}
	}
	return -1;
}

void CHrkObject::Destroy()
{

}

void CHrkObject::AddRef()
{
	::InterlockedIncrement( &m_RefCount );
}

int CHrkObject::GetRefCount()
{
	return m_RefCount;
}

void CHrkObject::Release()
{
	if( m_RefCount > 0){
		::InterlockedDecrement( &m_RefCount );
		if( m_RefCount == 0){
			Destroy();
		}
	}
}